<template>
  <div class="trend-chart-container">
    <div class="chart-header">
      <div class="chart-title">
        <el-icon><TrendCharts /></el-icon>
        <span>工单趋势</span>
      </div>
      <div class="chart-controls">
        <el-select v-model="selectedPeriod" @change="handlePeriodChange" size="small">
          <el-option label="最近7天" value="7d" />
          <el-option label="最近30天" value="30d" />
          <el-option label="最近90天" value="90d" />
        </el-select>
        <el-button-group class="chart-type-buttons">
          <el-button 
            :type="chartType === 'line' ? 'primary' : 'default'" 
            size="small"
            @click="setChartType('line')"
          >
            折线图
          </el-button>
          <el-button 
            :type="chartType === 'bar' ? 'primary' : 'default'" 
            size="small"
            @click="setChartType('bar')"
          >
            柱状图
          </el-button>
        </el-button-group>
      </div>
    </div>
    
    <div class="chart-wrapper">
      <canvas ref="chartCanvas" class="trend-chart" v-show="!chartError"></canvas>
      <div v-if="chartError" class="chart-error">
        <div class="error-icon">📊</div>
        <p>图表加载失败</p>
        <el-button size="small" @click="retryChart">重试</el-button>
      </div>
    </div>
    
    <div class="chart-legend">
      <div class="legend-item">
        <div class="legend-color created"></div>
        <span>创建工单</span>
        <span class="legend-value">{{ totalCreated }}</span>
      </div>
      <div class="legend-item">
        <div class="legend-color resolved"></div>
        <span>解决工单</span>
        <span class="legend-value">{{ totalResolved }}</span>
      </div>
      <div class="legend-item">
        <div class="legend-color pending"></div>
        <span>待处理</span>
        <span class="legend-value">{{ totalPending }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { TrendCharts } from '@element-plus/icons-vue'
import ChartCleanup from '../utils/chartCleanup'

export default {
  name: 'TrendChart',
  components: {
    TrendCharts
  },
  props: {
    tickets: {
      type: Array,
      default: () => []
    }
  },
  setup(props) {
    const chartCanvas = ref(null)
    const chartInstance = ref(null)
    const selectedPeriod = ref('7d')
    const chartType = ref('line')
    const chartError = ref(false)
    
    // 统计数据
    const totalCreated = ref(0)
    const totalResolved = ref(0)
    const totalPending = ref(0)
    
    // 生成模拟数据
    const generateMockData = (period) => {
      const days = period === '7d' ? 7 : period === '30d' ? 30 : 90
      const data = []
      const today = new Date()
      
      for (let i = days - 1; i >= 0; i--) {
        const date = new Date(today)
        date.setDate(date.getDate() - i)
        
        // 模拟数据：工作日工单较多，周末较少
        const isWeekend = date.getDay() === 0 || date.getDay() === 6
        const baseCreated = isWeekend ? 2 : 8
        const baseResolved = isWeekend ? 1 : 6
        
        const created = Math.max(0, baseCreated + Math.floor(Math.random() * 6) - 3)
        const resolved = Math.max(0, baseResolved + Math.floor(Math.random() * 4) - 2)
        const pending = Math.max(0, created - resolved + Math.floor(Math.random() * 3) - 1)
        
        data.push({
          date: date.toISOString().split('T')[0],
          created,
          resolved,
          pending
        })
      }
      
      return data
    }
    
    // 计算统计数据
    const calculateStats = (data) => {
      totalCreated.value = data.reduce((sum, item) => sum + item.created, 0)
      totalResolved.value = data.reduce((sum, item) => sum + item.resolved, 0)
      totalPending.value = data.reduce((sum, item) => sum + item.pending, 0)
    }
    
    // 安全创建图表
    const createChart = async () => {
      if (!chartCanvas.value) return
      
      try {
        chartError.value = false
        
        // 动态导入chart.js
        const { Chart, registerables } = await import('chart.js')
        Chart.register(...registerables)
        
        const data = generateMockData(selectedPeriod.value)
        calculateStats(data)
        
        const labels = data.map(item => {
          const date = new Date(item.date)
          return `${date.getMonth() + 1}/${date.getDate()}`
        })
        
        const createdData = data.map(item => item.created)
        const resolvedData = data.map(item => item.resolved)
        const pendingData = data.map(item => item.pending)
        
        // 安全的配置对象
        const config = {
          type: chartType.value,
          data: {
            labels: labels || [],
            datasets: [
              {
                label: '创建工单',
                data: createdData || [],
                borderColor: '#409eff',
                backgroundColor: 'rgba(64, 158, 255, 0.1)',
                borderWidth: 3,
                fill: chartType.value === 'line',
                tension: 0.4,
                pointBackgroundColor: '#409eff',
                pointBorderColor: '#ffffff',
                pointBorderWidth: 2,
                pointRadius: 6,
                pointHoverRadius: 8
              },
              {
                label: '解决工单',
                data: resolvedData || [],
                borderColor: '#67c23a',
                backgroundColor: 'rgba(103, 194, 58, 0.1)',
                borderWidth: 3,
                fill: chartType.value === 'line',
                tension: 0.4,
                pointBackgroundColor: '#67c23a',
                pointBorderColor: '#ffffff',
                pointBorderWidth: 2,
                pointRadius: 6,
                pointHoverRadius: 8
              },
              {
                label: '待处理',
                data: pendingData || [],
                borderColor: '#e6a23c',
                backgroundColor: 'rgba(230, 162, 60, 0.1)',
                borderWidth: 3,
                fill: chartType.value === 'line',
                tension: 0.4,
                pointBackgroundColor: '#e6a23c',
                pointBorderColor: '#ffffff',
                pointBorderWidth: 2,
                pointRadius: 6,
                pointHoverRadius: 8
              }
            ]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            animation: false, // 禁用动画避免错误
            interaction: {
              intersect: false,
              mode: 'index'
            },
            plugins: {
              legend: {
                display: false
              },
              tooltip: {
                enabled: true,
                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                titleColor: '#ffffff',
                bodyColor: '#ffffff',
                borderColor: '#409eff',
                borderWidth: 1,
                cornerRadius: 8,
                displayColors: true,
                callbacks: {
                  title: function(context) {
                    try {
                      const index = context[0]?.dataIndex
                      if (index !== undefined && data[index]) {
                        const date = new Date(data[index].date)
                        return date.toLocaleDateString('zh-CN', { 
                          month: 'long', 
                          day: 'numeric',
                          weekday: 'short'
                        })
                      }
                    } catch (error) {
                      console.warn('Tooltip title error:', error)
                    }
                    return ''
                  },
                  label: function(context) {
                    try {
                      const label = context.dataset?.label || ''
                      const value = context.parsed?.y || 0
                      return `${label}: ${value} 个`
                    } catch (error) {
                      console.warn('Tooltip label error:', error)
                    }
                    return ''
                  }
                }
              }
            },
            scales: {
              x: {
                grid: {
                  display: false
                },
                ticks: {
                  color: '#909399',
                  font: {
                    size: 12
                  }
                }
              },
              y: {
                beginAtZero: true,
                grid: {
                  color: 'rgba(0, 0, 0, 0.05)',
                  drawBorder: false
                },
                ticks: {
                  color: '#909399',
                  font: {
                    size: 12
                  },
                  callback: function(value) {
                    return value + ' 个'
                  }
                }
              }
            },
            elements: {
              bar: {
                borderRadius: 4,
                borderSkipped: false
              }
            }
          }
        }
        
        // 安全销毁现有实例
        if (chartInstance.value) {
          try {
            ChartCleanup.cleanupChartInstance(chartInstance.value)
          } catch (error) {
            console.warn('Chart destroy error:', error)
          }
          chartInstance.value = null
        }
        
        // 创建新实例
        chartInstance.value = new Chart(chartCanvas.value, config)
        
      } catch (error) {
        console.error('Failed to create chart:', error)
        chartError.value = true
      }
    }
    
    // 安全更新图表
    const updateChart = async () => {
      if (chartInstance.value && chartInstance.value.data && chartInstance.value.data.datasets) {
        try {
          const data = generateMockData(selectedPeriod.value)
          calculateStats(data)
          
          const labels = data.map(item => {
            const date = new Date(item.date)
            return `${date.getMonth() + 1}/${date.getDate()}`
          })
          
          const createdData = data.map(item => item.created)
          const resolvedData = data.map(item => item.resolved)
          const pendingData = data.map(item => item.pending)
          
          chartInstance.value.data.labels = labels
          if (chartInstance.value.data.datasets[0]) {
            chartInstance.value.data.datasets[0].data = createdData
          }
          if (chartInstance.value.data.datasets[1]) {
            chartInstance.value.data.datasets[1].data = resolvedData
          }
          if (chartInstance.value.data.datasets[2]) {
            chartInstance.value.data.datasets[2].data = pendingData
          }
          chartInstance.value.update('none') // 使用'none'模式避免动画错误
        } catch (error) {
          console.error('Failed to update chart:', error)
          // 如果更新失败，重新创建图表
          createChart()
        }
      }
    }
    
    // 切换图表类型
    const setChartType = (type) => {
      chartType.value = type
      createChart()
    }
    
    // 处理时间段变化
    const handlePeriodChange = () => {
      updateChart()
    }
    
    // 重试图表
    const retryChart = () => {
      createChart()
    }
    
    // 安全监听窗口大小变化
    const handleResize = () => {
      if (chartInstance.value && chartInstance.value.resize) {
        try {
          chartInstance.value.resize()
        } catch (error) {
          console.warn('Chart resize error:', error)
        }
      }
    }
    
    onMounted(() => {
      nextTick(() => {
        createChart()
        window.addEventListener('resize', handleResize)
      })
    })
    
    onUnmounted(() => {
      try {
        ChartCleanup.cleanupChartInstance(chartInstance.value)
        chartInstance.value = null
      } catch (error) {
        console.warn('Chart cleanup error:', error)
      }
      window.removeEventListener('resize', handleResize)
    })
    
    // 监听tickets变化
    watch(() => props.tickets, () => {
      updateChart()
    }, { deep: true })
    
    return {
      chartCanvas,
      selectedPeriod,
      chartType,
      chartError,
      totalCreated,
      totalResolved,
      totalPending,
      setChartType,
      handlePeriodChange,
      retryChart
    }
  }
}
</script>

<style scoped>
.trend-chart-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 12px;
  overflow: hidden;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.chart-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #1a202c;
}

.chart-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chart-type-buttons {
  border-radius: 6px;
  overflow: hidden;
}

.chart-wrapper {
  flex: 1;
  padding: 20px 24px;
  position: relative;
  min-height: 300px;
}

.chart-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 300px;
  color: #909399;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.chart-error p {
  margin: 8px 0 16px 0;
  font-size: 14px;
}

.trend-chart {
  width: 100% !important;
  height: 100% !important;
}

.chart-legend {
  display: flex;
  justify-content: center;
  gap: 32px;
  padding: 16px 24px 20px;
  background: #fafbfc;
  border-top: 1px solid #f0f0f0;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.legend-color.created {
  background: #409eff;
}

.legend-color.resolved {
  background: #67c23a;
}

.legend-color.pending {
  background: #e6a23c;
}

.legend-value {
  font-weight: 600;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chart-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .chart-controls {
    width: 100%;
    justify-content: space-between;
  }
  
  .chart-legend {
    flex-wrap: wrap;
    gap: 16px;
    justify-content: flex-start;
  }
  
  .chart-wrapper {
    min-height: 250px;
    padding: 16px;
  }
}

@media (max-width: 480px) {
  .chart-header {
    padding: 16px;
  }
  
  .chart-wrapper {
    min-height: 200px;
    padding: 12px;
  }
  
  .chart-legend {
    padding: 12px 16px;
    gap: 12px;
  }
  
  .legend-item {
    font-size: 13px;
  }
}
</style>